import dva from 'dva';
import { browserHistory } from 'dva/router';
import createLoading from 'dva-loading';
// import createLogger from 'redux-logger';
import { persistStore, createTransform, autoRehydrate } from 'redux-persist';

import persistHelper from './utils/persistHelper';
import './index.html';

const ERROR_MSG_DURATION = 3; // 3 秒

const isDev = process.env.NODE_ENV === 'development';

// 1. Initialize
const app = dva({
    extraEnhancers: [autoRehydrate()],
    history: browserHistory,
    // onAction: isDev ? createLogger() : () => {},
    onError() {
    // message.error(e.message, ERROR_MSG_DURATION);
    },
});

// 2. Plugins
app.use(createLoading());

// 3. Model
app.model(require('./models/recognize'));
app.model(require('./models/preview'));
app.model(require('./models/Editor/wizard'));
app.model(require('./models/Editor/editor'));
app.model(require('./models/Editor/dialog'));
app.model(require('./models/Editor/pages'));
app.model(require('./models/Editor/widgets'));
app.model(require('./models/Editor/timelines'));
app.model(require('./models/Editor/pageJump'));
app.model(require('./models/Editor/pageTimelines'));
app.model(require('./models/Editor/resourecs'));
app.model(require('./models/Editor/templates'));
app.model(require('./models/Editor/data'));

// 4. Router
if (isDev) app.router(require('./router'));
else app.router(require('./router.release'));

// 5. Start
app.start('#mainNode');

// 6. Persisit
const localData = {};
const specialSerialize = (inboundState, id, key) => {
    if (key === '@@dva') return inboundState;
    if (!localData[key]) localData[key] = {};
    localData[key][id] = inboundState;
    return localData[key];
};
const specialDeserialize = (outboundState, id, key) => {
    if (key === '@@dva') return outboundState['@@dva'];
    localData[key] = outboundState;
    return outboundState[id];
};

const persisitTransform = createTransform(
  (inboundState, key) => specialSerialize(inboundState, is.CONST.resource_picture_id, key),
  (outboundState, key) => specialDeserialize(outboundState, is.CONST.resource_picture_id, key),
);
persistHelper.start();

persistStore(app._store, { transforms: [persisitTransform], blacklist: ['editor','dialog'] }, () => {
    persistHelper.end();
});
